﻿using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
using System.Collections;
using System;
using SgLib;

//#if EASY_MOBILE
//using EasyMobile;
//#endif

public class UIManager : MonoBehaviour
{
    // 开始面板
    public GameObject UIBegin;
    public GameObject UIPlay;
    public GameObject UIEnd;

    public GameObject soundOnBtn;
    public GameObject soundOffBtn;


    public Button startBtn;

    public Button reStartBtn;

    [Header("Object References")]
    public GameObject header;
    public GameObject title;
    //最后结算界面中间的分数
    public Text score;

    public Text bestScore;
    public GameObject tapToStart;
    //public GameObject menuButtons;
    //public GameObject settingsUI;

    public GameObject scoreCirlces;
    public GameObject gamePlay;
    public GameObject mouseCheck;
    public CheckHit checkHit;


    public Text scoreTextWhenGameOver;
    public Text gameOverText;
    public Text bestScoreText;
    public GameObject bestText;


    // 成绩
    //public Text countText;
    public Image scoreCircleImageMaxValue;
    public Image scoreCircleImage;
    public Image scoreBestCircleImage;
    private Animator scoreAnimator;

    //看视频防止重复点击
    public float time;
    //视频剩余次数
    public int vedioShowNum;
    public Button tipsBtn;
    public Text tipsText;
    public VedioPanel vedioPanel;
    public SetUp setUp;
    public GameObject TipPopup;

    private static UIManager instance;

    public static UIManager Instance => instance;

    private void Awake()
    {
        instance = this;
    }
    void Start()
    {
        GameManager.GameStateChanged += OnGameStateChanged;
        ScoreManager.ScoreUpdated += OnScoreUpdated;


        scoreCircleImageMaxValue.fillAmount = 1;
        scoreCircleImage.fillAmount = 0;

        scoreAnimator = score.GetComponent<Animator>();


        this.UIBegin.SetActive(true);
        this.UIPlay.SetActive(false);
        this.UIEnd.SetActive(false);
        this.startBtn.onClick.AddListener(this.StartGame);
        this.tipsBtn.onClick.AddListener(this.ShowTips);
        this.reStartBtn.onClick.AddListener(this.RestartGame);

    }

    // Update is called once per frame
    void Update()
    {
        score.text = ScoreManager.Instance.Score.ToString();
        scoreTextWhenGameOver.text = ScoreManager.Instance.Score.ToString();
        bestScoreText.text = ScoreManager.Instance.HighScore.ToString();
        bestScore.text = ScoreManager.Instance.HighScore.ToString();
        //countText.text = (checkHit.numberOfHit - checkHit.hitCount).ToString();
        UpdateMuteButtons();
        //增加时间
        time += Time.deltaTime;
    }

    public void StartGame()
    {
        vedioShowNum = 2;
        time = 0;
        tipsText.text = vedioShowNum.ToString();
        GameManager.Instance.StartGame();
    }

    public void EndGame()
    {
        GameManager.Instance.GameOver();
    }

    public void RestartGame()
    {
        Debug.Log("重新开始游戏");
        GameObject[] tempObject = GameObject.FindGameObjectsWithTag("FocusGameObject");
        for (int i = 0; i < tempObject.Length; i++)
        {
            Destroy(tempObject[i]);
        }
        //重置个数控制
        checkHit.numberOfWinning = 0;
        setUp.tempNumberOfWinning = 0;


        GameManager.Instance.RestartGame();
    }

    //视频按钮点击
    public void ShowTips()
    {
        if (time < 1.3f)
            return;
        if (vedioShowNum == 0)
        {
            //vedioPanel.gameObject.SetActive(true);
            GameManager.Instance.checkHit.isClick = false;
            TipPopup.SetActive(true);
        }
        else
        {
            time = 0;
            vedioShowNum--;
            tipsText.text = vedioShowNum.ToString();
            GameManager.Instance.checkHit.ShowTips();
        }
    }


    void OnGameStateChanged(GameState newState, GameState oldState)
    {
        if (newState == GameState.Prepare)
        {
            Debug.Log("重新开始游戏");
            this.UIBegin.SetActive(true);
            this.UIPlay.SetActive(false);
            this.UIEnd.SetActive(false);
            this.mouseCheck.SetActive(false);

        }
        else if (newState == GameState.Playing)
        {
            Debug.Log("开始游戏");
            this.UIBegin.SetActive(false);
            this.UIPlay.SetActive(true);
            this.mouseCheck.SetActive(true);
            this.checkHit.Init();
        }
        else if (newState == GameState.PreGameOver)
        {
            // Before game over, i.e. game potentially will be recovered
        }
        else if (newState == GameState.GameOver)
        {
            Debug.Log("游戏结束3");
            StartCoroutine(CRShowGameOverUI());
        }
    }

    void OnScoreUpdated(int newScore)
    {
        scoreAnimator.Play("NewScore");
    }



    IEnumerator CRShowGameOverUI()
    {
        this.UIEnd.SetActive(true);
        float runTime = 1f;
        float pastTime = 0;
        float temp = (float)ScoreManager.Instance.Score / GameManager.Instance.maxScore;
        float temp2 = (float)ScoreManager.Instance.HighScore / GameManager.Instance.maxScore;
        scoreBestCircleImage.fillAmount = temp2;
        while (pastTime < runTime)
        {
            pastTime += Time.deltaTime;
            float t = pastTime / runTime;
            t = Mathf.Sin(t * Mathf.PI * 0.5f);
            scoreCircleImage.fillAmount = temp * t;
            scoreTextWhenGameOver.text = (Mathf.RoundToInt(t * ScoreManager.Instance.Score)).ToString();
            yield return null;
        }

        if (ScoreManager.Instance.HasNewHighScore)
        {
            gameOverText.text = "New Best Score!";
            SoundManager.Instance.PlaySound(SoundManager.Instance.newBest);
        }
        else
        {
            gameOverText.text = "Game Over";
        }

        gameOverText.gameObject.GetComponent<Animator>().Play("NewHighScoreAnim");

    }

    public void ShowCharacterSelectionScene()
    {
        SceneManager.LoadScene("CharacterSelection");
    }

    public void ToggleSound()
    {
        SoundManager.Instance.ToggleMute();
    }

    public void ToggleMusic()
    {
        SoundManager.Instance.ToggleMusic();
    }

    public void RateApp()
    {
        Utilities.RateApp();
    }

    public void OpenTwitterPage()
    {
        Utilities.OpenTwitterPage();
    }

    public void OpenFacebookPage()
    {
        Utilities.OpenFacebookPage();
    }

    public void ButtonClickSound()
    {
        Utilities.ButtonClickSound();
    }

    void UpdateMuteButtons()
    {
        if (SoundManager.Instance.IsMuted())
        {
            soundOnBtn.gameObject.SetActive(false);
            soundOffBtn.gameObject.SetActive(true);
        }
        else
        {
            soundOnBtn.gameObject.SetActive(true);
            soundOffBtn.gameObject.SetActive(false);
        }
    }



    /// <summary>
    /// 改变次数
    /// </summary>
    /// <param name="value"></param>
    public void changeVedioNum(int value)
    {
        vedioShowNum += value;
        tipsText.text = value.ToString();
    }

    bool IsPremiumFeaturesEnabled()
    {
        //return PremiumFeaturesManager.Instance != null && PremiumFeaturesManager.Instance.enablePremiumFeatures;
        return true;
    }

    public void TouchWatchAds()
    {
        TipPopup.SetActive(false);
        GameManager.Instance.checkHit.isClick = true;
        TopOnAdManager.Instance.ShowVideoAutoAd(() =>
        {
            Debug.Log("看完广告");
            changeVedioNum(1);
        });

        //string videoAdid = VideData.Instance.GetVide();
        //TTSDK.TTRewardedVideoAd r = AdMgr.Instance.ShowVideoAdNew(videoAdid);
        //GameManager.Instance.checkHit.isClick = true;
        ////创建激励视频关闭回调
        //r.OnClose += (bol, val) =>
        //{
        //    Debug.Log("关闭广告 ，是否已经看完" + bol);
        //    //看完广告获得提示
        //    if (bol)
        //    {
        //        changeVedioNum(1);
        //        MaidianNew.MaidianBackCallback(" ");
        //        Debug.Log("广告看完");
        //    }
        //    else
        //    {
        //        Debug.Log("广告未看完");
        //    }
        //};

        ////创建报错回调  
        //r.OnError += (code, errorMessage) =>
        //{

        //    Debug.Log("code:" + code + "错误信息：" + errorMessage);
        //};

        ////展示广告（新版本必须调用，不然无法展示出来广告）
        //r.Show();

    }
}
